package jdbc;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import static java.lang.String.format;
/*
* 基本crud
*
* */
public class GenericDao<T> extends BasicDao {
    // 插入操作
    public int insert(T entity) {

        String tableName = getTableName(entity.getClass());
        StringBuilder columnsBuilder = new StringBuilder();
        StringBuilder valuesBuilder = new StringBuilder();
        List<Object> parameters = new ArrayList<>();

        try {
            for (Field field : entity.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                if (!field.isSynthetic()) {
                    if (columnsBuilder.length() > 0) {
                        columnsBuilder.append(", ");
                        valuesBuilder.append(", ");
                    }
                    columnsBuilder.append(field.getName());
                    valuesBuilder.append("?");
                    parameters.add(field.get(entity));
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("访问实体字段时出错", e);
        }

        //构建一个sql语句
        String sql = format("INSERT INTO %s (%s) VALUES (%s)", tableName, columnsBuilder.toString(), valuesBuilder.toString());
        return update(sql, parameters.toArray());
    }

    // 账号删除
    public int delete(T entity, Object account) {
        String tableName = getTableName(entity.getClass());
        String sql = format("DELETE FROM %s WHERE account = ?", tableName);
        return update(sql, account);
    }

    public T findByAccountAndPassword(Class<T> entity, Object account, Object password, Object username) {
        String tableName = getTableName(entity);
        String sql = format("SELECT * FROM %s WHERE (account = ? OR username = ?) AND password = ?", tableName);
        return  querySingle(sql, createRowMapper(entity) , account, username, password);
    }

    public T findByAccount(Class<T> entityClass, Object account) {
        String tableName = getTableName(entityClass);
        String sql = format("SELECT * FROM %s WHERE account = ? OR username = ?", tableName);
        return querySingle(sql, createRowMapper(entityClass), account, account);
    }

    // 查询所有实体
    public List<T> findAll(Class<T> entityClass) {
        String tableName = getTableName(entityClass);
        String sql = format("SELECT * FROM %s", tableName);
        return queryMultiple(sql, createRowMapper(entityClass));
    }


    /*
     * 修改信息
     * */
    public int updateInfo(Class<T> entityClass, String username, String contact, String email, String password,int Id) {
        String tableName = getTableName(entityClass);
        String sql = format("UPDATE  %s SET username = ?, contact = ? ,email = ? , password = ? WHERE Id = ?", tableName);
        return update(sql, username, contact, email,password, Id);
    }
    public int updateById(T entity) {
        // 根据实体元数据生成 SQL UPDATE 语句
        String tableName = getTableName(entity.getClass());
        StringBuilder setBuilder = new StringBuilder();
        List<Object> parameters = new ArrayList<>();

        try {
            Object idValue = null;
            String idColumnName = null;
            //通过反射
            for (Field field : entity.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                if (!field.isSynthetic()) {
                    Object value = field.get(entity);
                    if (field.getName().equals("Id")) {
                        idColumnName = field.getName();
                        idValue = value;
                    } else {
                        if (setBuilder.length() > 0) {
                            setBuilder.append(", ");
                        }
                        setBuilder.append(field.getName()).append(" = ?");
                        parameters.add(value);
                    }
                }
            }

            if (idValue == null) {
                throw new IllegalArgumentException("实体没有 id 属性");
            }

            String sql = format("UPDATE %s SET %s WHERE %s = ?", tableName, setBuilder.toString(), idColumnName);
            parameters.add(idValue);
            return update(sql, parameters.toArray());
        } catch (IllegalAccessException e) {
            throw new RuntimeException("访问实体字段时出错", e);
        }
    }



    // 获取实体对应的表名
    private String getTableName(Class<?> entityClass) {
        // 简化处理，表名与类名相同
        return entityClass.getSimpleName();
    }


}
